﻿using ConsoleApp_client.Message;
using ConsoleApp_client.Message.Service2UI;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp_client
{
    class Program
    {
        static int saveImgCount = 0;

        static void Main(string[] args)
        {
        Attribute:
            Console.WriteLine("Hello World!");
            //string url = "http://localhost:5000/chatHub";
            string url = "http://127.0.0.1:9000/hubs/fr";
            var conBuilder = new HubConnectionBuilder();
            conBuilder.WithUrl(url);
            var _connection = conBuilder.Build();
            // _connection.ServerTimeout = TimeSpan.FromSeconds(8);
            //_connection.HandshakeTimeout = TimeSpan.FromSeconds(10);

            CancellationToken tocken = new CancellationToken()
            {

            };
        lab:
            try
            {
                _connection.StartAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"链接失败:{ex.Message}");
                Task.Delay(3000);
                goto lab;
            }
            _connection.Closed += ex =>
            {
                try
                {
                    _connection.StartAsync().Wait();
                    return System.Threading.Tasks.Task.CompletedTask;
                }
                catch (Exception)
                {

                    Task.Delay(3000);
                }
                return Task.CompletedTask;
            };

            _connection.On<object>("ReceiveMessageAsync", msg =>
            {
                Console.WriteLine($"{DateTime.Now} recv message :{msg}");
            });

            _connection.On<DateTime>("RefreshTime", time =>
            {

                Console.WriteLine($"{time}");
            });

           
            _connection.On<ServiceToUIMessageRefreshImage>("RefreshImage", imgMsg =>
            {
                if (imgMsg != null && imgMsg.JpegBuf != null)
                {
                    try
                    {
                        using var ms = new MemoryStream(imgMsg.JpegBuf);
                        Bitmap img = new Bitmap(ms);
                        if (saveImgCount<3)
                        {
                           // img.Save(saveImgCount + ".png");
                        }
                        Console.WriteLine($"{imgMsg.JpegBuf.Length}");
                    }
                    catch (Exception)
                    {
                    }

                    saveImgCount++;
                }



            });


            int count = 0;
            Task.Run(async () =>
            {
                while (true)
                {
                    Task.Delay(2000).Wait();
                    string msg = string.Empty;
                    if (count == 0)
                    {
                        await _connection.SendAsync("RefreshTime", new UIToServiceMessageRefreshTime());
                        msg = nameof(UIToServiceMessageRefreshTime);
                    }
                    else if (count == 1)
                    {
                        await _connection.SendAsync("OpenCamera", new UIToServiceMessageOpenCamera());
                        msg = nameof(UIToServiceMessageOpenCamera);
                    }
                    else if (count == 5)
                    {
                        await _connection.SendAsync("StopCamera", new UIToServiceMessageStopCamera());
                        msg = nameof(UIToServiceMessageStopCamera);
                    }
                    else if (count == 10)
                    {
                        //_connection.SendAsync("FaceDataRegister", new UIToServiceMessageRegister());
                        var falg = await _connection.InvokeAsync<bool>("FaceDataRegister", new UIToServiceMessageRegister());
                        msg = nameof(UIToServiceMessageRegister) + $"无参 结果:{falg}";
                        Console.WriteLine(_connection.State);
                    }
                    else if (count == 15)
                    {
                        //_connection.SendAsync("FaceDataRegister", new UIToServiceMessageRegister());
                        Console.WriteLine(_connection.State);
                        var imgBuf = EncodeJpeg(new Bitmap("People.png"));
                        Console.WriteLine(imgBuf.Length);
                        var list = new List<byte[]> { imgBuf };
                        var falg = await _connection.InvokeAsync<bool>("FaceDataRegister", new UIToServiceMessageRegister { CardNumber = "123", UserName = "wz", RegistJpegBufLS = list });
                        msg = nameof(UIToServiceMessageRegister) + $"有参 结果:{falg}";
                    }
                    else if (count == 18)
                    {
                        //_connection.SendAsync("FaceDataRegister", new UIToServiceMessageRegister());
                        Console.WriteLine(_connection.State);
                        var result = await _connection.InvokeAsync<ServiceToUIMessageDiscern>("FaceDataDiscern", new UIToServiceMessageDiscern() { JpegBuf = EncodeJpeg(new Bitmap("People.png")) });
                        msg = nameof(ServiceToUIMessageDiscern) + $"有参 结果:{result?.Name}";
                    }
                    else if (count == 20)
                    {
                        //_connection.SendAsync("FaceDataRegister", new UIToServiceMessageRegister());
                        Console.WriteLine(_connection.State);
                        var result = await _connection.InvokeAsync<bool>("DeleteFaceData", new UIToServiceMessageDelete() { CardNumber="123"});
                        msg = nameof(UIToServiceMessageDelete) + $" 结果:{result}";
                    }
                    else if (count == 23)
                    {
                        //_connection.SendAsync("FaceDataRegister", new UIToServiceMessageRegister());
                        Console.WriteLine(_connection.State);
                        var result = await _connection.InvokeAsync<bool>("UpdateFaceData", new UIToServiceMessageUpdate());
                        msg = nameof(UIToServiceMessageUpdate) + $" 结果:{result}";
                    }

                    count++;
                    if (!string.IsNullOrEmpty(msg))
                    {
                        Console.WriteLine($"{DateTime.Now} : {msg}");
                    }
                }
            });
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "q")
                {
                    break;
                }
                else if (input == "r")
                {
                    count = 0;
                }
                else if (input == "123")
                {
                    goto Attribute;
                }
            }

        }


        public static byte[] EncodeJpeg(Bitmap bitmap)
        {
            using MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            return ms.ToArray();
        }
    }
}
